package com.adam.masterSpringMVC4.weibo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
public class ParallelSearchService {

    @Autowired
    private AsyncSearch asyncSearch;

    public List<WeiboData> search(String searchType, List<String> keywords) {
        CountDownLatch latch = new CountDownLatch(keywords.size());
        List<WeiboData> allWeibos = Collections.synchronizedList(new ArrayList<>());
        keywords.stream()
                .forEach(keyword -> asyncFetch(latch, allWeibos, searchType, keyword));
        await(latch);
        return allWeibos;
    }

    private void asyncFetch(CountDownLatch latch, List<WeiboData> allWeibos, String searchType, String keyword) {
        asyncSearch.asyncFetch(searchType, keyword)
                .addCallback(weibos -> onSuccess(allWeibos, latch, weibos),
                        ex -> onError(latch, ex));
    }

    private void await(CountDownLatch latch) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void onSuccess(List<WeiboData> results, CountDownLatch latch, List<WeiboData> weibos) {
        results.addAll(weibos);
        latch.countDown();
    }

    private void onError(CountDownLatch latch, Throwable ex) {
        ex.printStackTrace();
        latch.countDown();
    }

}
